package com.laomuji.android.mvvm.http.encrypt

import android.util.Base64
import java.io.ByteArrayOutputStream
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.X509EncodedKeySpec
import java.util.Arrays
import javax.crypto.Cipher

/**
 * 对字符串进行RSA加密
 * @author laomuji666
 * @since 2024/2/20
 */
object RsaEncrypt : BaseEncrypt  {
    //公钥
    private const val PUBLIC_KEY = ""
    private const val MAX_ENCRYPT_BLOCK = 117

    override fun encrypt(body: String): String {
        return try {
            encryptWithKey(body)
        } catch (e: Exception) {
            body
        }
    }

    private fun encryptWithKey(text: String): String {
        val decodeData = Base64.decode(PUBLIC_KEY, Base64.DEFAULT)
        val pubKey = KeyFactory.getInstance("RSA")
            .generatePublic(X509EncodedKeySpec(decodeData)) as RSAPublicKey
        val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
        cipher.init(Cipher.ENCRYPT_MODE, pubKey)
        val data = text.toByteArray()
        val inputLen = data.size
        val out = ByteArrayOutputStream()
        var offSet = 0
        var cache: ByteArray
        var i = 0
        //  对数据分段加密
        while (inputLen - offSet > 0) {
            cache = if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK)
            } else {
                cipher.doFinal(data, offSet, inputLen - offSet)
            }
            out.write(cache, 0, cache.size)
            i++
            offSet = i * MAX_ENCRYPT_BLOCK
        }
        val encryptedData = out.toByteArray()
        out.close()
        return Arrays.toString(Base64.encode(encryptedData, Base64.DEFAULT))
    }
}